<template>
  <el-button type="primary" size="default" @click="emit('setState', 1)" icon="ele-Plus">
    添加SPU
  </el-button>

  <el-table :data="spuPageList" border stripe :style="{ margin: '30px 0' }">
    <el-table-column label="序号" type="index" width="80" />
    <el-table-column prop="spuName" label="SPU名称"></el-table-column>
    <el-table-column prop="description" label="SPU描述"></el-table-column>
    <el-table-column label="操作">
      <template v-slot="{ row }">
        <el-button type="primary" size="default" @click="" icon="ele-Plus"></el-button>
        <el-button type="primary" size="default" @click="emit('setState', 1, row)" icon="ele-Edit"></el-button>
        <el-button type="info" size="default" @click="" icon="ele-Warning"></el-button>
        <el-button type="danger" size="default" @click="" icon="ele-Delete"></el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination v-model:page-size="limit" v-model:current-page="page" :page-sizes="[3, 5, 7, 9]" :total="total"
    :page-count="5" layout="prev, pager, next, sizes" />
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "SpuList",
});
</script>

<script setup lang="ts">
import { ref, watch } from "vue";
import useAttrListStore from "@/stores/attr";
import { storeToRefs } from "pinia";
import type { SpuInfoType } from "@/api/spu";
import { requestSpuPageList } from "@/api/spu";

//接收自定义事件
const emit = defineEmits<{ (event: "setState", state: number,  row?: SpuInfoType ): void }>();

const limit = ref(3);
const page = ref(1);
const total = ref(0);

//从pinia中拿到category3Id
const attrStore = useAttrListStore();
//解构category3Id
const { category3Id } = storeToRefs(attrStore);

//声明数据保存spu分页列表
const spuPageList = ref<SpuInfoType[]>([]);
//封装spu分页列表的请求函数
const getSpuPageList = async () => {
  try {
    const result = await requestSpuPageList(
      page.value,
      limit.value,
      category3Id.value as number
    );
    spuPageList.value = result.records;
    total.value = result.total;
  } catch (error) {
    ElMessage.error("请求spu分页");
  }
};

//监听category3Id的变化,发送请求
watch(
  category3Id,
  () => {
    //如果category3Id没有值,则清空上一次的数据,并退出函数执行
    if (category3Id.value === null) {
      spuPageList.value = [];
      total.value = 0;
      return;
    }
    getSpuPageList();
  },
  //初始化时立即执行一次,防止路由跳转再次进入视图后没有数据
  { immediate: true }
);
</script>
